<template>
    <div class="yieldAnalysis">
        <el-row :gutter="20">
            <el-col :span="show ? rowObj.T1 : rowObj.F1" :xs="show ? rowObj.T2 : rowObj.F2">
                <workSiteLeft ref="workSiteLeft" :show="show" @showLeft="showLeft" @queryVal="queryVal" />
            </el-col>
            <el-col :span="show ? rowObj.T3 : rowObj.F3" :xs="show ? rowObj.T4 : rowObj.F4">
                <div class="container-body" ref="clientBox">
                    <el-form :inline="true" :model="searchForm" size="small" class="mySearch">
                        <el-button style="margin: 3px 8px 0 0;" size="mini"
                            :icon="show ? 'el-icon-s-fold' : 'el-icon-s-unfold'" circle @click="showLeft(show)"></el-button>
                        <el-form-item label="拌合楼">
                            <el-select style="width: 160px" v-model="searchForm.stationCode" clearable size="mini"
                                placeholder="请选择拌合楼">
                                <el-option v-for="item in cementListData" :key="item.id" :label="item.name"
                                    :value="item.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
                        </el-form-item>
                    </el-form>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="chartBox">
                                <div id="yearChart" style="width: 100%; height: 100%;transform-origin: 0 0;">
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="chartBox">
                                <div id="monthChart" style="width: 100%; height: 100%;transform-origin: 0 0;">
                                </div>
                                <div class="chartSearch">
                                    <el-date-picker v-model="monthForm.year" style="width: 100px" @change="getListForMonth"
                                        type="year" format="yyyy" value-format="yyyy" size="small" placeholder="选择年">
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="24">
                            <div class="chartBox">
                                <div id="dayChart" style="width: 100%; height: 100%;transform-origin: 0 0;">
                                </div>
                                <div class="chartSearch">
                                    <el-date-picker v-model="dayForm.month" style="width: 120px" @change="getListForDay"
                                        type="month" format="yyyy-MM" value-format="yyyy-MM" size="small" placeholder="选择月">
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="chartBoxHeight">
                                <div id="matchChart" style="width: 100%; height: 100%;transform-origin: 0 0;">
                                </div>
                                <div class="chartSearch">
                                    <el-date-picker v-model="matchForm.year" style="width: 100px" @change="getListForMatch"
                                        type="year" format="yyyy" value-format="yyyy" size="small" placeholder="选择年">
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="chartBoxHeight">
                                <div id="projectChart" style="width: 100%; height: 100%;transform-origin: 0 0;">
                                </div>
                                <div class="chartSearch">
                                    <el-date-picker v-model="projectForm.year" style="width: 100px"
                                        @change="getListForProject" type="year" format="yyyy" value-format="yyyy"
                                        size="small" placeholder="选择年">
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
  
<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import {
    cementList,
    getLastData,
    listForYear,
    listForMonth,
    listForDay,
    listForProject,
    listForMatch
} from "@/api/waterStability/statistics/yieldAnalysis";
import workSiteLeft from "@/views/components/workSiteLeft";

export default {
    name: 'yieldAnalysis', // 产量统计分析
    components: {
        workSiteLeft
    },
    data() {
        return {
            show: false,
            rowObj: {
                T1: 3,
                T2: 24,
                T3: 21,
                T4: 24,
                F1: 0,
                F2: 0,
                F3: 24,
                F4: 24,
            },
            cementListData: [],
            zoom: 1,
            chartWidth: 0,
            chartHeight: 0,
            searchForm: { stationCode: undefined },
            yearForm: { stationCode: undefined },
            monthForm: { stationCode: undefined, year: undefined },
            dayForm: { stationCode: undefined, month: undefined },
            matchForm: { stationCode: undefined, year: undefined },
            projectForm: { stationCode: undefined, year: undefined },
            yearChart: null,
            monthChart: null,
            dayChart: null,
            matchChart: null,
            projectChart: null
        };
    },
    beforeDestroy() {
        // window.removeEventListener('resize', this.resize);
    },
    mounted() {
        // window.addEventListener('resize', this.resize);
        setTimeout(() => {
            this.init();
        }, 500);
    },
    methods: {
        showLeft(show) {
            this.show = !show;
        },
        queryVal(val) {
            this.searchForm.id = val.id;
            this.yearForm.id = val.id;
            this.monthForm.id = val.id;
            this.dayForm.id = val.id;
            this.matchForm.id = val.id;
            this.projectForm.id = val.id;
            this.onSearch(true);
        },
        // 查询拌合楼下拉列表
        getCementList() {
            cementList().then((res) => {
                this.cementListData = res.data || [];
            });
        },
        init() {
            // 查询数据
            this.onSearch(true);
        },
        /**
         * 页面变化监听
         */
        resize() {
            this.$nextTick(() => {
                this.zoom = 1 / this.$store.state.d2admin.zoomGlobal.zoom;
                this.chartHeight = 100 * window.devicePixelRatio;
                this.chartWidth = 100 * window.devicePixelRatio;

                if (null != this.yearChart) {
                    this.yearChart.resize();
                }
                if (null != this.monthChart) {
                    this.monthChart.resize();
                }
                if (null != this.dayChart) {
                    this.dayChart.resize();
                }
                if (null != this.matchChart) {
                    this.matchChart.resize();
                }
                if (null != this.projectChart) {
                    this.projectChart.resize();
                }
            });
        },

        /**
         * 执行查询
         */
        async onSearch() {
            let year = undefined;
            let month = undefined;
            let stationCode = undefined;
            await getLastData(this.searchForm).then((res) => {
                if (!!res.data) {
                    stationCode = res.data.stationCode;
                    let dischargeTime = res.data.dischargeTime;
                    if (19 == dischargeTime.length) {
                        year = dischargeTime.substring(0, 4);
                        month = dischargeTime.substring(0, 7);
                    }
                }
            });

            if (null == this.searchForm.stationCode || undefined == this.searchForm.stationCode) {
                this.searchForm.stationCode = stationCode;
            }

            this.yearForm.stationCode = stationCode;
            this.getListForYear();

            this.monthForm.stationCode = stationCode;
            this.monthForm.year = year;
            this.getListForMonth();

            this.dayForm.stationCode = stationCode;
            this.dayForm.month = month;
            this.getListForDay();

            this.matchForm.stationCode = stationCode;
            this.matchForm.year = year;
            this.getListForMatch(year);

            this.projectForm.stationCode = stationCode;
            this.projectForm.year = year;
            this.getListForProject();
        },

        /**
         * 获取历年产量数据
         */
        getListForYear() {
            if (!!this.yearForm.stationCode) {
                listForYear(this.yearForm)
                    .then((res) => {
                        this.createYearChart(res.data);
                    })
                    .catch(() => {
                        this.createYearChart(undefined);
                    });
            } else {
                this.createYearChart(undefined);
            }
        },

        /**
         * 创建历年产量报表
         */
        createYearChart(data) {
            console.log(data);
            if (null == this.yearChart) {
                this.yearChart = echarts.init(document.getElementById('yearChart'));
            } else {
                this.yearChart.clear();
            }

            let title = '历年产量统计';
            let xData = [];
            let sData = [];
            if (!!data) {
                data.forEach((item) => {
                    xData.push(item.label);
                    sData.push(item.value);
                });
            }
            let option = this.getBarOption(title, '年份', xData, sData, ['#44CCF9']);
            this.yearChart.setOption(option);
        },

        /**
         * 获取月产量数据
         */
        getListForMonth() {
            let title = '月产量统计';
            if (!!this.monthForm.stationCode && !!this.monthForm.year) {
                title = this.monthForm.year + '年' + title;
                listForMonth(this.monthForm)
                    .then((res) => {
                        this.createMonthChart(title, res.data);
                    })
                    .catch(() => {
                        this.createMonthChart(title, undefined);
                    });
            } else {
                this.createMonthChart(title, undefined);
            }
        },

        /**
         * 创建月产量报表
         */
        createMonthChart(title, data) {
            if (null == this.monthChart) {
                this.monthChart = echarts.init(document.getElementById('monthChart'));
            } else {
                this.monthChart.clear();
            }

            let xData = [];
            let sData = [];
            if (!!data) {
                data.forEach((item) => {
                    xData.push(item.label);
                    sData.push(item.value);
                });
            }
            let option = this.getBarOption(title, '月份', xData, sData, ['#20BE97']);
            this.monthChart.setOption(option);
        },

        /**
         * 获取日产量数据
         */
        getListForDay() {
            let title = '日产量统计';
            if (!!this.dayForm.stationCode && !!this.dayForm.month) {
                title = this.dayForm.month + '月' + title;
                listForDay(this.dayForm)
                    .then((res) => {
                        this.createDayChart(title, res.data);
                    })
                    .catch(() => {
                        this.createDayChart(title, undefined);
                    });
            } else {
                this.createDayChart(title, undefined);
            }
        },

        /**
         * 创建日产量报表
         */
        createDayChart(title, data) {
            if (null == this.dayChart) {
                this.dayChart = echarts.init(document.getElementById('dayChart'));
            } else {
                this.dayChart.clear();
            }

            let xData = [];
            let sData = [];
            if (!!data) {
                data.forEach((item) => {
                    xData.push(item.label);
                    sData.push(item.value);
                });
            }
            let option = this.getLineOption(title, '日期', xData, sData);
            this.dayChart.setOption(option);
        },

        /**
         * 获取各配方产量数据
         */
        getListForMatch() {
            let title = '配方产量统计';
            if (!!this.matchForm.stationCode && !!this.matchForm.year) {
                title = this.matchForm.year + '年' + title;
                listForMatch(this.matchForm)
                    .then((res) => {
                        this.createMatchChart(title, res.data);
                    })
                    .catch(() => {
                        this.createMatchChart(title, undefined);
                    });
            } else {
                this.createMatchChart(title, undefined);
            }
        },

        /**
         * 创建各配方产量报表
         */
        createMatchChart(title, data) {
            if (null == this.matchChart) {
                this.matchChart = echarts.init(document.getElementById('matchChart'));
            } else {
                this.matchChart.clear();
            }

            let total = 0;
            let sData = [];
            if (!!data) {
                data.forEach((item) => {
                    total += item.value;
                    sData.push({
                        value: item.value,
                        name: item.label ? item.label : '--'
                    });
                });
            }
            total = total.toFixed(2);
            let option = this.getPieOption(title, '配方', total, sData);
            this.matchChart.setOption(option);
        },

        /**
         * 获取各项目产量数据
         */
        getListForProject() {
            let title = '项目产量统计';
            if (!!this.projectForm.stationCode && !!this.projectForm.year) {
                title = this.projectForm.year + '年' + title;
                listForProject(this.projectForm)
                    .then((res) => {
                        this.createProjectChart(title, res.data);
                    })
                    .catch(() => {
                        this.createProjectChart(title, undefined);
                    });
            } else {
                this.createProjectChart(title, undefined);
            }
        },

        /**
         * 创建日产量报表
         */
        createProjectChart(title, data) {
            if (null == this.projectChart) {
                this.projectChart = echarts.init(document.getElementById('projectChart'));
            } else {
                this.projectChart.clear();
            }

            let total = 0;
            let sData = [];
            if (!!data) {
                data.forEach((item) => {
                    total += item.value;
                    sData.push({
                        value: item.value,
                        name: item.label ? item.label : '--'
                    });
                });
            }
            total = total.toFixed(2);
            let option = this.getPieOption(title, '项目', total, sData);
            this.projectChart.setOption(option);
        },

        /**
         * 获取图表配置信息
         */
        getBarOption(title, xName, xData, sData, colors = []) {
            let option = {
                color: colors,
                title: {
                    text: title,
                    textStyle: {
                        padingLeft: 100
                    }
                },
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                legend: {
                    data: ['实际重量（吨）', '运单重量（吨）'],
                    right: 160
                },
                xAxis: {
                    name: xName,
                    data: xData,
                    axisLine: { onZero: true },
                    splitLine: { show: false },
                    splitArea: { show: false },
                    axisLabel: {
                        rotate: 45,
                        formatter: (value, index) => {
                            return value;
                        }
                    }
                },
                yAxis: {
                    name: '单位(吨)',
                    axisLabel: {
                        formatter: (value, index) => {
                            if (index == 0) {
                                return '';
                            }

                            if (!!value) {
                                if (value >= 10000) {
                                    return value / 10000 + '万';
                                }
                            }
                            return value;
                        }
                    }
                },
                grid: {
                    top: 60,
                    bottom: 100,
                    left: 60,
                    right: 60
                },
                series: [
                    {
                        name: '产量（吨）',
                        type: 'bar',
                        barGap: '0%',
                        barMaxWidth: 30,
                        data: sData,
                        itemStyle: {
                            // normal: {
                            //     label: {
                            //         show: true,
                            //         position: 'top',
                            //         textStyle: {
                            //             color: '#000000'
                            //         }
                            //     }
                            // }
                        }
                    }
                ]
            };
            return option;
        },

        /**
         * 获取图表配置信息
         */
        getLineOption(title, xName, xData, sData) {
            let option = {
                title: {
                    text: title,
                    textStyle: {
                        padingLeft: 100
                    }
                },
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    name: xName,
                    data: xData,
                    axisLine: { onZero: true },
                    splitLine: { show: false },
                    splitArea: { show: false },
                    axisLabel: {
                        rotate: 45,
                        formatter: (value, index) => {
                            return value;
                        }
                    }
                },
                yAxis: {
                    name: '单位(吨)',
                    axisLabel: {
                        formatter: (value, index) => {
                            if (index == 0) {
                                return '';
                            }

                            if (!!value) {
                                if (value >= 10000) {
                                    return value / 10000 + '万';
                                }
                            }
                            return value;
                        }
                    }
                },
                grid: {
                    top: 60,
                    bottom: 100,
                    left: 60,
                    right: 60
                },
                series: [
                    {
                        data: sData,
                        type: 'line',
                        smooth: true,
                        itemStyle: {
                            color: '#409EFF'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: '#409EFF'
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(64,158,255,0)'
                                }
                            ])
                        }
                    }
                ]
            };
            return option;
        },

        /**
         * 获取图表配置信息
         */
        getPieOption(title, xName, total, sData) {
            let colors = [
                '#409EFF',
                '#20BE97',
                '#FED363',
                '#FE7682',
                '#55B5FF',
                '#81EF98',
                '#FFAC4C',
                '#FF606A',
                '#7871FF',
                '#AFD1FF',
                '#25D4A9',
                '#FE8238',
                '#FF2728',
                '#EB9AFF',
                '#00E2CE',
                '#95D600',
                '#FFD39C',
                '#FF4D4D',
                '#FF9BC1',
                '#0A60B8'
            ];
            let option = {
                title: [
                    {
                        text: title,
                        textStyle: {
                            padingLeft: 100
                        }
                    },
                    {
                        text: '总产量',
                        subtext: total,
                        top: '45%',
                        left: '45%',
                        textAlign: 'center',
                        textStyle: {
                            color: '#666666',
                            fontSize: 14
                        },
                        subtextStyle: {
                            color: '#333333',
                            fontSize: 24
                        }
                    }
                ],
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    icon: 'circle',
                    orient: 'vertical',
                    left: '80%',
                    top: 60,
                    bottom: 100
                },
                grid: {
                    top: 60,
                    bottom: 100,
                    left: 60,
                    right: 60
                },
                series: [
                    {
                        name: xName,
                        color: colors,
                        type: 'pie',
                        center: ['45%', '50%'],
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        labelLine: {
                            show: false
                        },
                        data: sData
                    },
                    {
                        name: '',
                        color: ['#F1F5F8'],
                        type: 'pie',
                        center: ['20%', '50%'],
                        radius: ['40%', '50%'],
                        avoidLabelOverlap: false,
                        silent: true,
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        data: [total]
                    }
                ]
            };

            return option;
        }
    }
};
</script>


<style scoped>
.yieldAnalysis {
    padding: 10px;
}

.chartBox {
    height: 350px;
    width: 100%;
    position: relative;
}

.chartBoxHeight {
    height: 400px;
    width: 100%;
    position: relative;
}

.chartSearch {
    position: absolute;
    top: 0px;
    right: 60px;
}
</style>

<style scoped lang="scss" ></style>
  

